package com.JWH_TV.utils

import android.util.Base64
import java.nio.charset.Charset
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

class DecryptUtils {

    companion object {
        private const val password = "TP25076786123456"

        fun decryptPassword(encryptedPassword: String): String {
            return try {
                val key = SecretKeySpec(password.toByteArray(Charset.forName("UTF-8")), "AES")
                val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
                cipher.init(Cipher.DECRYPT_MODE, key)

                val encryptedParts = encryptedPassword.split(",")
                val decryptedParts = encryptedParts.map { part ->
                    val encryptedBytes = Base64.decode(part, Base64.DEFAULT)
                    val decryptedBytes = cipher.doFinal(encryptedBytes)
                    String(decryptedBytes, Charset.forName("UTF-8"))
                }

                decryptedParts.joinToString(",")
            } catch (e: Exception) {
                e.printStackTrace()
                ""
            }
        }

        fun decryptUrl(encryptedUrl: String): String {
            return try {
                val key = SecretKeySpec(password.toByteArray(Charset.forName("UTF-8")), "AES")
                val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
                cipher.init(Cipher.DECRYPT_MODE, key)

                val encryptedParts = encryptedUrl.split(",")
                val decryptedParts = encryptedParts.map { part ->
                    val encryptedBytes = Base64.decode(part, Base64.DEFAULT)
                    val decryptedBytes = cipher.doFinal(encryptedBytes)
                    String(decryptedBytes, Charset.forName("UTF-8"))
                }

                decryptedParts.joinToString(",")
            } catch (e: Exception) {
                e.printStackTrace()
                ""
            }
        }

//        fun parseMultipleStreams(decryptedUrl: String): Pair<List<String>, List<String>> {
//            val hdPattern = "(hd\\d+):https?://[\\w.]+(?:/[^,]+)?(?:,|$)"
//            val sdPattern = "(sd\\d+):https?://[\\w.]+(?:/[^,]+)?(?:,|$)"
//
//            val hdRegex = Regex(hdPattern)
//            val sdRegex = Regex(sdPattern)
//
//            val hdStreams = hdRegex.findAll(decryptedUrl)
//                .map { it.value.substringAfter(":") }
//                .filter { it.isNotEmpty() }
//                .toList()
//
//            val sdStreams = sdRegex.findAll(decryptedUrl)
//                .map { it.value.substringAfter(":") }
//                .filter { it.isNotEmpty() }
//                .toList()
//
//            return Pair(hdStreams, sdStreams)
//        }
    }
}
